package com.wolf.util;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Properties文件读写工具
 *
 * @author sdyang
 * @create 2017-11-12 16:58
 **/
public class PropertiesUtil {

    private final static String UTF8 = "utf-8";

    /**
     * @param filePath
     * @return
     */
    public static Map<String, String> read(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("找不到文件" + filePath);
            return null;
        }
        return read(file);
    }

    /**
     * @param file
     * @return
     */
    public static Map<String, String> read(File file) {
        Map<String, String> dataMap = new HashMap<String, String>();

        try {
            Properties pps = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream(file));

            pps.load(new InputStreamReader(in, UTF8));

            Enumeration en = pps.propertyNames(); //得到配置文件的名字

            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String value = pps.getProperty(key);
                dataMap.put(key, value);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataMap;

    }


    /**
     * @param filePath
     * @param key
     * @return
     */
    public static String read(String filePath, String key) {
        Properties props = new Properties();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(
                    filePath));
            props.load(new InputStreamReader(in, UTF8));
            String value = props.getProperty(key);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param filePath
     * @param key
     * @param value
     */
    public static void update(String filePath, String key, String value) {
        Properties props = new Properties();
        try {
            Map<String, String> keyValueMap = read(filePath);
            keyValueMap.put(key, value);

            props.load(new FileInputStream(filePath));
            OutputStream fos = new FileOutputStream(filePath, false);
            for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
                props.put(entry.getKey(), entry.getValue());
            }
            props.store(new OutputStreamWriter(fos, UTF8), "Update '" + key + "' value");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
